<?php
/**
 * User: Hufeng
 * Date: 2017/08/29 19:48
 * Desc: 用户Model
 */
namespace App\Model;
use SasPHP\SqlModel;

class TradeUserAssetLogModel extends SqlModel{
    protected $dbName = 'trade_user_asset_log';

    public function __construct(){
        parent::__construct('DB_SERVER');
    }

    function insertData($data){
        $this->dbConn->insert($this->dbName,$data);
        return $this->dbConn->id();
    }

    function editData($where,$data){
        $this->dbConn->update($this->dbName,$data,$where);
    }

    function delData($data){
        $this->dbConn->delete($this->dbName, $data);
    }

    function findData($where,$fields='*'){
        $res = $this->dbConn->get($this->dbName,$fields,$where);
        return $res;
    }

    function queryData($where,$fields='*'){
        $res = $this->dbConn->select($this->dbName,$fields,$where);
        return $res;
    }
    //获取统计数据
    public function getTotalNum($where){
        $res = $this->dbConn->count($this->dbName,$where);
        return $res;
    }
    //sum数据
    public function sumData($where,$param){
        $res = $this->dbConn->sum($this->dbName,$param,$where);
        return $res;
    }

    //增加更新用户持仓
    public function editUserHold($uid,$sid,$num,$price){
        $data = $this->findData(['uid'=>$uid,'sid'=>$sid]);
        if($data){
            $totalPrice = round(($price*$num)+($data['havenum']*$data['avg_price']),2);
            $totalNum = $num+$data['havenum'];
            $avgPrice = round($totalPrice/$totalNum,2);
            $this->editData(['id'=>$data['id']],['havenum'=>$totalNum,'avg_price'=>$avgPrice]);
        }else{
            $this->insertData(['uid'=>$uid,'sid'=>$sid,'havenum'=>$num,'avg_price'=>$price]);
        }
    }
    //委托交易
    public function dgTrade($uid,$sid,$num){
        $res = $this->findData(['uid'=>$uid,'sid'=>$sid]);
        if($res['havenum']<$num){
            return false;
        }
        //更新用户持仓
        $where = ['id'=>$res['id']];
        $eData = ['havenum[-]'=>$num];
        $this->editData($where,$eData);

        //记录用户股票变动明细
        $ualModel = new TradeUser();
        $ualData = [
            'uid'=>$uid,
            'change_money'=>-$money,
            'left_money'=>$leftMoney,
            'type'=>$type,
            'status'=>$status,
            'addtime'=>date('Y-m-d H:i:s'),
            'memo'=>$memo
        ];
        $ualModel->insertData($ualData);
        return true;
    }
}
